//
//  ClubSquareForumCell.swift
//  77Club
//
//  Created by Apple on 2024/9/6.
//

import UIKit
import VersaPlayer
import MediaPlayer

class ClubSquareForumCell: UITableViewCell, RaeNetworkProtocol {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let nameImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let titleImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
            .color(.black).font(12.font_semiBold).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(16.font_semiBold).end()
    private let contentLabel = c_make_ex(UITextView.self)
        .color("#47494D").font(15.font_medium).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let browseImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_look").end()
    private let commitImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_commit").end()
    private let likeImageView = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    private let browseLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).text("999浏览").end()
    private let commitLikeLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).alignment(.right).end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("Mine_Commit_more").end()
    private let justImageV = c_make_ex(UIImageView.self)
        .image("Square_detail_justFabu").end()
    
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let voiceButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_aloud").image("Dynamic_detail_slience", state: .selected).end()
    private let playTimeLabel = UIIconButton(style: .leading(itemSpace: 2))
    
    private var imgTapValue = [String]()
    private var topicTapValue = [String]()
    private var postTapValue = [String]()
    private var showCount = 0
    private var isPlaying = true
    
    var aa: (() -> Void)?
    
    var model: ClubGameCommunityListModel?{
        didSet{
            guard let md = model else { return }

            iconImageView.loadImage(url: md.face)
            nameLabel.text = md.fabu
            if md.user_role == 1 {
                nameImageView.widthConstraint?.constant = 26.0.Scale
                nameImageView.heightConstraint?.constant = 16.0.Scale
                nameImageView.image = "Square_detail_master".toImage
                nameLabel.leadingConstraint?.constant = 2.0.Scale
            }else if md.user_role == 2{
                nameImageView.widthConstraint?.constant = 30.0.Scale
                nameImageView.heightConstraint?.constant = 14.0.Scale
                nameImageView.image = "Square_detail_admin".toImage
                nameLabel.leadingConstraint?.constant = 2.0.Scale
            }else{
                nameImageView.widthConstraint?.constant = 0
                nameImageView.heightConstraint?.constant = 0
                nameImageView.image = "".toImage
                nameLabel.leadingConstraint?.constant = 0
            }
            var content = md.content + " "
            if md.content_h5.count > 0 {
                content = md.content_h5 + " "
            }
            let attrString = self.createAttributedText(from: content)
            contentLabel.attributedText = attrString
            let time = ClubGlobalTool.shared.timeDescription(from: md.time, 2)
            timeLabel.text = time
            if time == "刚刚" {
                justImageV.isHidden = false
                iconImageView.frame.origin.y = 32.0.Scale
                nameLabel.topConstraint?.constant = 33.0.Scale
                moreButton.topConstraint?.constant = 36.0.Scale
            }else{
                justImageV.isHidden = true
                iconImageView.frame.origin.y = 16.0.Scale
                nameLabel.topConstraint?.constant = 17.0.Scale
                moreButton.topConstraint?.constant = 20.0.Scale
            }
            if md.look == "0" {
                browseLabel.text = "浏览"
            }else{
                browseLabel.text = md.look + "浏览"
            }
            var pinglun = md.pinglun
            if pinglun == "0"{
                pinglun = ""
            }
            var good = md.good
            if good == "0"{
                good = ""
            }
            commitLikeLabel.text = pinglun + "评论 · " + good + "点赞"
            likeImageView.isSelected = md.is_good
            playerView.isHidden = true
            collectionView.isHidden = false
            playerView.heightConstraint?.constant = 0
            browseImageView.topConstraint?.constant = 0
            if md.video.count > 0 {
                playerView.isHidden = false
                collectionView.isHidden = true
                collectionView.heightConstraint?.constant = 0
                playerView.heightConstraint?.constant = 152.0.Scale
                browseImageView.topConstraint?.constant = 152.0.Scale
                if let url = URL.init(string: md.video) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        self.playerView.pause()
                        self.voiceButton.isSelected = false
                    }
                }
                self.showCount = 0
            }else if md.image.count == 1 {
                collectionView.heightConstraint?.constant = 152.0.Scale
                self.showCount = 1
            }else if md.image.count == 2 {
                collectionView.heightConstraint?.constant = 85.0.Scale
                self.showCount = 2
            }else if md.image.count > 2 {
                let w = (CGFloat.screenWidth - 110.0.Scale)/3
                if md.image.count == 3 || md.image.count == 4 || md.image.count == 5 {
                    collectionView.heightConstraint?.constant = w
                    self.showCount = 3
                }else if md.image.count == 6 || md.image.count == 7 || md.image.count == 8 {
                    collectionView.heightConstraint?.constant = w * 2 + 2
                    self.showCount = 6
                }else{
                    collectionView.heightConstraint?.constant = w * 3 + 4
                    self.showCount = 9
                }
            }else{
                collectionView.heightConstraint?.constant = 0
            }
            let size = CGSize(width: CGFloat.screenWidth - 104.0.Scale, height: .greatestFiniteMagnitude)
            let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
                // 使用 boundingRect 方法计算高度
            let boundingRect = contentLabel.attributedText.boundingRect(with: size, options: options, context: nil)
            self.contentLabel.heightConstraint?.constant = ceil(boundingRect.height)
            
            if md.is_best == 1 {
                titleImageView.widthConstraint?.constant = 26.0.Scale
                titleImageView.image = "Square_detail_topLogo".toImage
                titleLabel.leadingConstraint?.constant = 2.0.Scale
            }else{
                titleImageView.widthConstraint?.constant = 0
                titleImageView.image = "".toImage
                titleLabel.leadingConstraint?.constant = 0
            }
            titleLabel.text = md.title
            
            
            
            collectionView.reloadData()
        }
    }
    
    var topicModel: ClubSquareTopicDataModel?{
        didSet{
            guard var md = topicModel else { return }
            // 将模型转换为 JSON 字符串
            md.is_best = "0"
            md.image = md.img
            let jsonString = md.kj.JSONObject()
            model = jsonString.kj.model(ClubGameCommunityListModel.self)
        }
    }
    
    /// 更多
    var showMoreView: ((_ model: ClubGameCommunityListModel) -> Void)?
    var showTopicMoreView: ((_ model: ClubSquareTopicDataModel) -> Void)?
    var zanButtonClick:((_:String)->())?
    var jumpToDetail:((_:String, _ uid: String)->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 点击视频
    var didSelectVideo:((_:String)->())?
    /// 话题主页
    var toTopicDetailVC: ((_ topicId: String) -> Void)?
    /// 游戏详情
    var toGameDetailVC: ((_ gameId: String) -> Void)?
    /// 用户主页
    var otherUserInfoVC: ((_ uid: String) -> Void)?
        
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            backView.subviews{
                moreButton
//                iconImageView
                nameImageView
                nameLabel
                timeLabel
                titleImageView
                titleLabel
                contentLabel
                collectionView
                playerView
                browseImageView
                commitImageView
                likeImageView
                browseLabel
                commitLikeLabel
            }
            justImageV
        }
        
        iconImageView.frame = CGRect(x: 12.0.Scale, y: 16.0.Scale, width: 40.0.Scale, height: 40.0.Scale)
        backView.addSubview(iconImageView)
        
        backView.leading(12.0.Scale).trailing(12.0.Scale).top(0).bottom(12.0.Scale)
        justImageV.leading(8.0.Scale).top(8.0.Scale).width(60.0.Scale).height(25.0.Scale)
        nameLabel.trailing(65.0.Scale).top(17.0.Scale)
        nameLabel.Leading == nameImageView.Trailing
        nameImageView.leading(64.0.Scale).width(30.0.Scale).height(16.0.Scale)
        nameImageView.CenterY == nameLabel.CenterY
        timeLabel.leading(64.0.Scale).trailing(65.0.Scale)
        timeLabel.Top == nameLabel.Bottom + 5.0.Scale
        moreButton.trailing(16.0.Scale).size(32.0.Scale).top(20.0.Scale)
        titleLabel.trailing(16.0.Scale).height(24.0.Scale)
        titleLabel.Top == iconImageView.Bottom + 4.0.Scale
        titleImageView.leading(64.0.Scale).width(26.0.Scale).height(16.0.Scale)
        titleImageView.CenterY == titleLabel.CenterY
        titleLabel.Leading == titleImageView.Trailing
        contentLabel.leading(64.0.Scale).top(88.0.Scale).trailing(16.0.Scale).height(36.0.Scale)
        contentLabel.Top == titleLabel.Bottom + 1.0.Scale
        collectionView.leading(64.0.Scale).trailing(16.0.Scale).height(0)
        collectionView.Top == contentLabel.Bottom + 8.0.Scale
        playerView.leading(64.0.Scale).trailing(16.0.Scale).height(0)
        playerView.Top == contentLabel.Bottom + 8.0.Scale
        browseImageView.leading(52.0.Scale).size(44.0.Scale)
        browseImageView.Top == collectionView.Bottom
        likeImageView.trailing(4.0.Scale).size(44.0.Scale)
        likeImageView.CenterY == browseImageView.CenterY
        commitImageView.size(44.0.Scale)
        commitImageView.CenterY == likeImageView.CenterY
        commitImageView.Trailing == likeImageView.Leading
        browseLabel.leading(64.0.Scale).bottom(15.0.Scale)
        browseLabel.Top == browseImageView.Bottom
        commitLikeLabel.trailing(16.0.Scale)
        commitLikeLabel.CenterY == browseLabel.CenterY
        
        backView.translatesAutoresizingMaskIntoConstraints = false
        
        playerView.use(controls: controls)
        playerView.layer.cornerRadius = 8.0.Scale
        playerView.layer.masksToBounds = true
        
        justImageV.isHidden = true
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2.0.Scale
        layout.minimumInteritemSpacing = 2.0.Scale
        layout.scrollDirection = .vertical
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 64.0.Scale, bottom: 0, right: 15.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameCircleCell.self, forCellWithReuseIdentifier: ClubGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.isScrollEnabled = false
        collectionView.delegate = self
        collectionView.dataSource = self
                
        let tapG = UITapGestureRecognizer.init(target: self, action: #selector(commentButtonClick))
        commitImageView.isUserInteractionEnabled = true
        commitImageView.addGestureRecognizer(tapG)
        likeImageView.addTarget(self, action: #selector(likeButtonClick), for: .touchUpInside)
        
        contentLabel.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        contentLabel.addGestureRecognizer(tapGesture)
        
        contentLabel.isEditable = false
        contentLabel.isScrollEnabled = false
        contentLabel.isUserInteractionEnabled = true
        contentLabel.backgroundColor = .clear
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.textContainerInset = .zero
        contentLabel.textContainer.lineFragmentPadding = 0
               
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        iconImageView.isUserInteractionEnabled = true
        let iconTap = UITapGestureRecognizer(target: self, action: #selector(clickUserIcon))
        iconImageView.addGestureRecognizer(iconTap)
        
        playerView.backgroundColor = .black
        playerView.playbackDelegate = self
        playerView.controls?.behaviour.shouldHideControls = false
        controls.subviews{
            voiceButton
            playTimeLabel
        }
        voiceButton.trailing(56).size(24)
        voiceButton.isSelected = true
        voiceButton.addTarget(self, action: #selector(clickVoiceButton), for: .touchUpInside)
        playTimeLabel.trailing(12).bottom(10).height(12.0.Scale)
        voiceButton.CenterY == playTimeLabel.CenterY
                
        playTimeLabel.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Dynamic_time".toImage, for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.titleLabel?.font = 10.font_semiBold
            v.isUserInteractionEnabled = false
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopAudioPlayer), name: .stopForumAudioPlayer, object: nil)
    }
    
    @objc private func commentButtonClick() {
        guard let md = model else { return }
        jumpToDetail?(md.id,md.uid)
    }
    
    @objc private func likeButtonClick(){
//        zanButtonClick?(model?.id ?? "")
        guard let md = model else { return }
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                ToastUtil.show()
                let res = await self.network.request(.likeStrategyPost(pid: md.id, puid: "", type: "0"))
                ToastUtil.dismiss()
                if res.isSuccess {
                    likeImageView.isSelected = !likeImageView.isSelected
                    let strArray = commitLikeLabel.text!.components(separatedBy: " · ")
                    var zanString = strArray.last ?? ""
                    if zanString == "点赞" {
                        zanString = "1点赞"
                    }else{
                        if likeImageView.isSelected {
                            zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                        }else{
                            zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                            if zanString == "0点赞"{
                                zanString = "点赞"
                            }
                        }
                    }
                    var pinglun = md.pinglun
                    if pinglun == "0"{
                        pinglun = ""
                    }
                    commitLikeLabel.text = pinglun + "评论 · " + zanString
                }
                
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func clickUserIcon(){
        otherUserInfoVC?(model?.uid_des ?? "")
    }
    
    @objc private func clickMoreButton(){
        if let md = model {
            showMoreView?(md)
        }
        
        if let md = topicModel {
            showTopicMoreView?(md)
        }
    }
    
    private func createAttributedText(from text: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(.foregroundColor, value: "#47494D".toColor, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(.font, value: 15.font_regular!, range: NSRange(location: 0, length: attributedString.length))
        
        let nsText = text as NSString
        var count = 0
        var offset = 0 // 偏移量
        var index = 0  // 用于生成唯一的 actionType 标识
        
        // 正则匹配 [图片] 和 #标签
        let hashtagRegex = try! NSRegularExpression(pattern: "#[^\\s]+", options: [])
        let imageTextRegex = try! NSRegularExpression(pattern: "\\[图片\\](\\S+?) ", options: [])
        let postTagRegex = try! NSRegularExpression(pattern: "\\+\\S+", options: [])
        
        // **1. 优先处理 #标签**
        let hashtagMatches = hashtagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in hashtagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let hashtagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard hashtagRange.location >= 0,
                  hashtagRange.location + hashtagRange.length <= attributedString.length else { continue }
            if var substring = attributedString.attributedSubstring(from: hashtagRange).string as String? {
                if let subjects = model?.subjects {
                    if substring.hasPrefix("#") {
                        substring.removeFirst()
                    }
                    if subjects.contains(where: { $0.name == substring }) {
                        index += 1
                        self.topicTapValue.append("hashtag_\(index)")
                        attributedString.addAttribute(.foregroundColor, value: "#E57617".toColor, range: hashtagRange) // 设置颜色
                        attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "hashtag_\(index)", range: hashtagRange)
                    }
                }
            }
        }
        
        // **2. 优先处理 +标签**
        let posttagMatches = postTagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in posttagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let posttagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard posttagRange.location >= 0,
                  posttagRange.location + posttagRange.length <= attributedString.length else { continue }
            if var substring = attributedString.attributedSubstring(from: posttagRange).string as String? {
                if let bbss = model?.bbss {
                    if substring.hasPrefix("+") {
                        substring.removeFirst()
                    }
                    if bbss.contains(where: { $0.title == substring && $0.news_id != "0" }) {
                        index += 1
                        self.postTapValue.append("posttag_\(index)")
                        attributedString.addAttribute(.foregroundColor, value: "#1280E5".toColor, range: posttagRange) // 设置颜色
                        attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "posttag_\(index)", range: posttagRange)
                    }
                }
            }            
        }
        
        // **3. 处理 [图片]**
        let imageTextMatches = imageTextRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in imageTextMatches {
            let fullMatchRange = NSRange(location: match.range(at: 0).location + offset, length: match.range(at: 0).length)
            let textRange = NSRange(location: match.range(at: 1).location + offset, length: match.range(at: 1).length)
            
            // 替换 [图片] 为图片
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: "Square_gameTag") // 替换为图片
            attachment.bounds = CGRect(x: 0, y: -7, width: 20, height: 20)
            let imageString = NSAttributedString(attachment: attachment)
            
            attributedString.replaceCharacters(in: NSRange(location: fullMatchRange.location, length: "[图片]".count), with: imageString)
            offset += imageString.length - "[图片]".count // 更新偏移量
            
            // 设置图片后面的文字颜色
            let updatedTextRange = NSRange(location: textRange.location + offset + (3 * count), length: textRange.length)
            if updatedTextRange.location + updatedTextRange.length <= attributedString.length {
                index += 1
                self.imgTapValue.append("imageText_\(index)")
                attributedString.addAttribute(.foregroundColor, value: "#3D9399".toColor, range: updatedTextRange)
                attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "imageText_\(index)", range: updatedTextRange)
            }
            count += 1
        }
        
        return attributedString
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: contentLabel)
        
        // 获取点击位置的字符索引
        if let position = contentLabel.closestPosition(to: location) {
            let characterIndex = contentLabel.offset(from: contentLabel.beginningOfDocument, to: position)
            
            // 确保 characterIndex 不超过富文本长度
            if characterIndex < contentLabel.attributedText.length {
                
                // 获取点击位置的属性
                let attributes = contentLabel.attributedText.attributes(at: characterIndex, effectiveRange: nil)
                
                // 检查是否存在 "actionType" 属性
                if let actionType = attributes[NSAttributedString.Key("actionType")] as? String {
                    if actionType.hasPrefix("hashtag_") {
                        print("The string starts with 'hashtag_'")
                        if let index = self.topicTapValue.firstIndex(of: actionType) {
                            if let gamesId = model?.subjects?[index].subject_id {
                                self.toTopicDetailVC?(gamesId)
                            }
                        }
                    }else if actionType.hasPrefix("imageText_")  {
                        // 执行对应的操作
                        if let index = self.imgTapValue.firstIndex(of: actionType) {
                            if let gamesId = model?.games?[index].gid {
                                self.toGameDetailVC?(gamesId)
                            }
                        }
                    }else if actionType.hasPrefix("posttag_")  {
                        // 执行对应的操作
                        if let index = self.postTapValue.firstIndex(of: actionType) {
                            if let postM = model?.bbss?[index] {
                                let gamesId = postM.news_id
                                let uid = postM.uid
                                self.jumpToDetail?(gamesId,uid)
                            }
                        }
                    }
                }else{
                    guard let md = model else { return }
                    self.jumpToDetail?(md.id, md.uid)
                }
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

extension ClubSquareForumCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, VersaPlayerPlaybackDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.showCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameCircleCell.description(), for: indexPath) as? ClubGameCircleCell else { return UICollectionViewCell() }
        pageCell.forumModel = model
        if model?.image.count ?? 0 > 0{
            pageCell.imageView.loadImage(url: model?.image[indexPath.row])
            pageCell.layoutIfNeeded()
            let count = model?.image.count ?? 0
            pageCell.isHiddenMore = true
            if self.showCount == 1 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8.0.Scale)
            }else if self.showCount == 2 {
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
                }else {
                    pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
                }
            }else if self.showCount == 3{
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
                }else {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
                if count - self.showCount > 0 && indexPath.row == 2 {
                    pageCell.isHiddenMore = false
                    pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
                }else{
                    pageCell.isHiddenMore = true
                }
            }else if self.showCount == 6{
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
                }else if indexPath.row == 3 {
                    pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 5 {
                    pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
                }else{
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
                if count - self.showCount > 0 && indexPath.row == 5 {
                    pageCell.isHiddenMore = false
                    pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
                }else{
                    pageCell.isHiddenMore = true
                }
            }else {
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
                }else if indexPath.row == 6 {
                    pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 8 {
                    pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
                }else{
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        if model?.video.count ?? 0 > 0 {
            return .zero
        }else if model?.image.count == 1 {
            return CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        }else if model?.image.count == 2{
            return CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 85.0.Scale)
        }else if model?.image.count ?? 0 > 2 {
            let w = (CGFloat.screenWidth - 110.0.Scale)/3
            return CGSize (width: w, height: w)
        }else{
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if model?.video.count ?? 0 > 0 {
            didSelectVideo?((model?.video)!)
        }else{
            didSelectImage?(indexPath.row,model?.image ?? [])
        }
    }
    
    @objc private func clickVoiceButton(){
        self.voiceButton.isSelected = !self.voiceButton.isSelected
        if self.voiceButton.isSelected {
            playerView.player.volume = 0
        }else{
            playerView.player.volume = 1
        }
    }
    
    func playVideo() {
        if let video = model?.video, video.count > 0 {
            playerView.play()
            playerView.player.volume = voiceButton.isSelected ? 0 : 1
        }
    }
        
    func pauseVideo() {
        if let video = model?.video, video.count > 0 {
            playerView.pause()
        }
    }
    
    @objc private func stopAudioPlayer(){
        pauseVideo()
    }
    
    func timeDidChange(player: VersaPlayer, to time: CMTime) {

        let currentT = CMTimeGetSeconds(time)
        let currentTStr = Int(currentT).toPlayTimeStr()
        playTimeLabel.setTitle(currentTStr, for: .normal)
    }
}


//MARK: 装备资料cell UICollectionViewDelegateFlowLayout
class ClubForumEquipCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource, HorizontalWaterfallLayoutDelegate {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var isWhite = false
    var news: [ClubStrategyBlockItemModel]?{
        didSet{
            collectionView.reloadData()
        }
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            collectionView
        }
        
        let layout = HorizontalWaterfallLayout()
        layout.delegate = self
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubForumEquipItemCell.self, forCellWithReuseIdentifier: ClubForumEquipItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.isScrollEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.leading(12.0.Scale).trailing(0).bottom(0).top(0.Scale).height(64.0.Scale)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return news?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubForumEquipItemCell.description(), for: indexPath) as? ClubForumEquipItemCell else { return UICollectionViewCell() }
        cell.model = news?[indexPath.row]
        cell.isWhite = self.isWhite
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let infoID = news?[indexPath.row].news_id ?? ""
        let dict = ["infoID": infoID]
        NotificationCenter.default.post(name: .forumToGameDetailVC, object: nil, userInfo: dict)
    }
    
    // MARK: - HorizontalWaterfallLayoutDelegate
    func collectionView(_ collectionView: UICollectionView, layout: HorizontalWaterfallLayout, widthForItemAt indexPath: IndexPath) -> CGFloat {
        // 返回动态宽度
        let name = news?[indexPath.row].title ?? ""
        let font = 12.font_regular
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width + 24.0.Scale
        return width
    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
//        return 8.0 // 固定间距
//    }
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        return UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 12.0.Scale) // 添加右边距
//    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


//MARK: 主线图⽂攻略cell
class ClubForumImageTextCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var isWhite = false
    var news: [ClubStrategyBlockItemModel]?{
        didSet{
            collectionView.reloadData()
        }
    }    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        subviews{
            collectionView
        }
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 0)
        layout.itemSize = CGSize(width: 120.0.Scale, height: 175.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubForumImageTextItemCell.self, forCellWithReuseIdentifier: ClubForumImageTextItemCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.leading(0).trailing(0).bottom(0).top(0.Scale).height(175.0.Scale)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return news?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubForumImageTextItemCell.description(), for: indexPath) as? ClubForumImageTextItemCell else { return UICollectionViewCell() }
        cell.model = news?[indexPath.row]
        cell.isWhite = self.isWhite
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let infoID = news?[indexPath.row].news_id ?? ""
        let dict = ["infoID": infoID]
        NotificationCenter.default.post(name: .forumToGameDetailVC, object: nil, userInfo: dict)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

//MARK: 装备资料cell
class ClubForumEquipItemCell: UICollectionViewCell {
    
//    private let bgView = c_make_ex(UIView.self)
//        .bgColor("#F7F8FA").corner(4.0.Scale).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(12.font_regular)
        .bgColor("#F7F8FA").corner(4.0.Scale).alignment(.center).end()
    
    var model: ClubStrategyBlockItemModel?{
        didSet{
            guard let md = model else { return }
            nameLabel.text = md.title
        }
    }
    
    var isWhite = false {
        didSet{
            if isWhite {
                nameLabel.backgroundColor = .white
            }else{
                nameLabel.backgroundColor = "#F7F8FA".toColor
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            nameLabel
        }
             
        nameLabel.fillContainer()
//        nameLabel.leading(12.0.Scale).trailing(12.0.Scale).centerVertically()
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 主线图⽂攻略cell
class ClubForumImageTextItemCell: UICollectionViewCell {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA").corner(12.0.Scale).end()
    private let iconImageV = c_make_ex(UIImageView.self)
        .corner(8.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(13.font_regular).alignment(.center)
        .text("主线图文攻略主线图文攻略").end()
    
    var model: ClubStrategyBlockItemModel?{
        didSet{
            guard let md = model else { return }
            iconImageV.loadImage(url: md.image)
            nameLabel.text = md.title
        }
    }
    
    var isWhite = false {
        didSet{
            if isWhite {
                backView.backgroundColor = .white
            }else{
                backView.backgroundColor = "#F7F8FA".toColor
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            backView.subviews{
                iconImageV
                nameLabel
            }
        }
                
        backView.fillContainer()
        iconImageV.leading(8.0.Scale).trailing(8.0.Scale).top(8.0.Scale).height(130.0.Scale)
        nameLabel.leading(8.0.Scale).trailing(8.0.Scale)
        nameLabel.Top == iconImageV.Bottom + 8.0.Scale
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 官方、活动
class ClubSquareForumActiveCell: UITableViewCell {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(12.font_semiBold).end()
    private let tagLabel = c_make_ex(UILabel.self)
        .color("#FF9900").font(8.font_medium).text("平台官方")
        .corner(4).border("#FF9900", width: 0.6).alignment(.center).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(16.font_semiBold).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(15.font_medium)
        .line(3).end()
    private let contentImage = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8).end()
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let browseImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_look").end()
    private let commitImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_commit").end()
    private let likeImageView = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    private let browseLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).text("999浏览").end()
    private let commitLikeLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).alignment(.right).end()
    
    var model: ClubGameCommunityListModel?{
        didSet{
            guard let md = model else { return }

            iconImageView.loadImage(url: md.face)
            nameLabel.text = md.fabu
            titleLabel.text = md.title
            contentLabel.text = md.content
            timeLabel.text = md.time
            if md.look == "0" {
                browseLabel.text = "浏览"
            }else{
                browseLabel.text = md.look + "浏览"
            }
            var pinglun = md.pinglun
            if pinglun == "0"{
                pinglun = ""
            }
            var good = md.good
            if good == "0"{
                good = ""
            }
            commitLikeLabel.text = pinglun + "评论 · " + good + "点赞"
            likeImageView.isSelected = md.is_good
//            if md.video.count > 0 {
//                playerView.isHidden = false
//                contentImage.isHidden = false
//                if let url = URL.init(string: md.video) {
//                    let item = VersaPlayerItem(url: url)
//                    playerView.set(item: item)
//                    playerView.play()
//                }
//                contentImage.heightConstraint?.constant = 152.0.Scale
//            }else 
            if md.image.count > 0 {
                playerView.isHidden = true
                contentImage.isHidden = false
                
                contentImage.loadImage(url: md.image.first)
                contentImage.heightConstraint?.constant = 152.0.Scale
            }else{
                playerView.isHidden = true
                contentImage.isHidden = true
                contentImage.heightConstraint?.constant = 0
            }
        }
    }
    
    var zanButtonClick:((_:String)->())?
    var jumpToDetail:((_:String)->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 点击视频
    var didSelectVideo:((_:String)->())?
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            backView.subviews{
                iconImageView
                nameLabel
                tagLabel
                timeLabel
                titleLabel
                contentLabel
                contentImage.subviews{
                    playerView
                }
                browseImageView
                commitImageView
                likeImageView
                browseLabel
                commitLikeLabel
            }
        }
        
        backView.leading(12.0.Scale).trailing(12.0.Scale).top(0).bottom(12.0.Scale)
        iconImageView.leading(16.0.Scale).top(16.0.Scale).size(40.0.Scale)
        nameLabel.leading(64.0.Scale).top(20.0.Scale).width(<=300.0.Scale)
        tagLabel.width(40.0.Scale)
        tagLabel.Leading == nameLabel.Trailing + 4.0.Scale
        tagLabel.CenterY == nameLabel.CenterY
        timeLabel.leading(64.0.Scale).top(41.0.Scale).trailing(30.0.Scale)
        titleLabel.leading(16.0.Scale).top(64.0.Scale).trailing(16.0.Scale)
        contentLabel.leading(16.0.Scale).top(85.0.Scale).trailing(16.0.Scale)
        contentImage.leading(16.0.Scale).trailing(16.0.Scale).height(152.0.Scale)
        contentImage.Top == contentLabel.Bottom + 8.0.Scale
        playerView.fillContainer()
        browseImageView.leading(16.0.Scale).size(44.0.Scale)
        browseImageView.Top == contentImage.Bottom
        likeImageView.trailing(16.0.Scale).size(44.0.Scale)
        likeImageView.CenterY == browseImageView.CenterY
        commitImageView.size(44.0.Scale)
        commitImageView.CenterY == likeImageView.CenterY
        commitImageView.Trailing == likeImageView.Leading
        browseLabel.leading(16.0.Scale).bottom(15.0.Scale)
        browseLabel.Top == browseImageView.Bottom
        commitLikeLabel.trailing(16.0.Scale)
        commitLikeLabel.CenterY == browseLabel.CenterY
        
                
        playerView.use(controls: controls)
        let tapG = UITapGestureRecognizer.init(target: self, action: #selector(commentButtonClick))
        let selImgTap = UITapGestureRecognizer.init(target: self, action: #selector(selImage))
        commitImageView.isUserInteractionEnabled = true
        contentImage.isUserInteractionEnabled = true
        commitImageView.addGestureRecognizer(tapG)
        contentImage.addGestureRecognizer(selImgTap)
        likeImageView.addTarget(self, action: #selector(likeButtonClick), for: .touchUpInside)
    }
    
    @objc private func commentButtonClick() {
        jumpToDetail?(model?.id ?? "")
    }
    
    @objc private func likeButtonClick(){
        zanButtonClick?(model?.id ?? "")
    }
    
    @objc private func selImage(){
        didSelectImage?(0,model?.image ?? [])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


//MARK: empty
class ClubSquareForumEmptyCell: UITableViewCell {
    
    private let emptyView = ClubEmptyView()
    
    var titleString: String = "" {
        didSet{
            emptyView.titleString = titleString
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            emptyView
        }
        
        emptyView.leading(0).trailing(0).top(100).bottom(0).height(310)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}


class HorizontalWaterfallLayout: UICollectionViewLayout {
    weak var delegate: HorizontalWaterfallLayoutDelegate?
    
    private var attributesCache: [UICollectionViewLayoutAttributes] = []
    private var contentWidth: CGFloat = 0
    private let rowCount = 2
    private let rowSpacing: CGFloat = 8
    private let itemSpacing: CGFloat = 8
    
    override func prepare() {
        super.prepare()
        
        guard let collectionView = collectionView, let delegate = delegate else { return }
        
        attributesCache.removeAll()
        contentWidth = 0
        
        let collectionViewHeight = collectionView.bounds.height
        let rowHeight = (collectionViewHeight - rowSpacing) / CGFloat(rowCount)
        
        var xOffsets: [CGFloat] = .init(repeating: 0, count: rowCount)
        var yOffsets: [CGFloat] = (0..<rowCount).map { CGFloat($0) * (rowHeight + rowSpacing) }
        
        for section in 0..<collectionView.numberOfSections {
            for item in 0..<collectionView.numberOfItems(inSection: section) {
                let indexPath = IndexPath(item: item, section: section)
                let itemWidth = delegate.collectionView(collectionView, layout: self, widthForItemAt: indexPath)
                
                // 找到最短的列（行）
                let rowIndex = xOffsets.firstIndex(of: xOffsets.min() ?? 0) ?? 0
                
                let frame = CGRect(x: xOffsets[rowIndex], y: yOffsets[rowIndex], width: itemWidth, height: rowHeight)
                let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
                attributes.frame = frame
                attributesCache.append(attributes)
                
                xOffsets[rowIndex] += itemWidth + itemSpacing
                contentWidth = max(contentWidth, xOffsets[rowIndex])
            }
        }
    }
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: contentWidth, height: collectionView?.bounds.height ?? 0)
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attributesCache.filter { $0.frame.intersects(rect) }
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return attributesCache.first { $0.indexPath == indexPath }
    }
}

protocol HorizontalWaterfallLayoutDelegate: AnyObject {
    func collectionView(_ collectionView: UICollectionView, layout: HorizontalWaterfallLayout, widthForItemAt indexPath: IndexPath) -> CGFloat
}

